package com.ruoyi.base.redis.login;

import com.alibaba.fastjson.JSON;
import com.ruoyi.platform.system.user.pojo.LoginUserDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * 登录redis
 *
 * @author lcf
 */
@Component
public class LoginRedis {
    @Autowired
    public StringRedisTemplate redisTemplate;

    /**
     * 过期时间单位
     */
    private TimeUnit timeUnit = TimeUnit.MINUTES;

    /**
     * 删除缓存
     */
    public void delCache(String userKey) {
        redisTemplate.delete(userKey);
    }

    /**
     * 缓存当前登录用户
     */
    public void cache(String userKey, LoginUserDTO user, long cacheTime) {
        redisTemplate.boundValueOps(userKey).set(JSON.toJSONString(user), cacheTime, timeUnit);
    }

    /**
     * 获取当前登录用户
     */
    public LoginUserDTO getLoginUser(String userKey) {
        String json = redisTemplate.boundValueOps(userKey).get();
        if (json != null) {
            return JSON.parseObject(json, LoginUserDTO.class);
        }

        return null;
    }
}
